<?php

class Painel_ProdutoController extends App_Controller_Action
{

    private $_table     = 'PRODUTO';
    private $_pk        = 'PRO_ID';
    private $_order_col = 'PRO_NOM';
    private $_order     = 'ASC';
    private $_sta_col   = 'PRO_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'PRO_FILE'; 
    public  $dir = 'public/upload/produto/';
    public  $db = '';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Painel_Form_Produto();        
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('tools','library');
        
        $where = 'WHERE '.$this->_pk . ' > 0';
        
        $dscfiltro = $this->_getParam('dscfiltro', '');
        if($dscfiltro > '') $where .= ' and PRO_NOM like "%'. $dscfiltro.'%" ';
        $this->view->dscfiltro = $dscfiltro;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_pdr.js');
       
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('tools','library');
        
        //$this->view->view = 'view';
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    $data = $this->form->getValues();
                    
                    unset($data['img']);
                    unset($data[$this->_file_col]);
                    unset($data['br']);
                    unset($data['barra']);
                    
                    $data['PRO_VLRCST'] = tools::money_to_float($data['PRO_VLRCST']);
                    $data['PRO_VLRVND'] = tools::money_to_float($data['PRO_VLRVND']);
                    
                    $this->db->beginTransaction();
                    if($id == 0){
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();   
                        imagem::rename($id,$this->dir,$returnImg['filenew']);    
                    }
                    else $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                    
                    foreach(glob($this->dir.$id.'.*') as $img) imagem::reize($img,$img,'400','400');
                    
                    if(strlen($data['PRO_CODBAR']) > 1){
                        require_once 'library/barcode.inc.php';
                        $code_number = str_pad($data['PRO_CODBAR'],13,'0',STR_PAD_LEFT);
                        new barCodeGenrator($code_number,1,$this->dir.$id.'_bar.gif', 200, 80, true);
                    }
                    
                    $this->verificarProdutoEstoque($id);
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');           
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                //Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id);
                $data['PRO_VLRCST'] = tools::float_to_money($data['PRO_VLRCST']);
                $data['PRO_VLRVND'] = tools::float_to_money($data['PRO_VLRVND']);
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        
        if((int) $id > 0 ) {  
            $this->db->beginTransaction();
            try {
                $ok = (bool) $this->db->delete('ESTOQUE', $this->_pk . ' = ' . $id);
                
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                
                if($ok){
                    Zend_Loader::loadClass('imagem','library');
                    imagem::delete($id,$this->dir,TRUE);
                    
                    foreach (glob($dir.$id.'_.*') as $file) unlink($file);
                }
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }      
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    function verificarProdutoEstoque($id = 0){
        
        $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM ESTOQUE WHERE '.$this->_pk . ' = ' . $id);
        
        if($data[$this->_pk] <= 0){
            
            $arr = array(
                $this->_pk      => $id,
                'EST_QTDMIN'    => '1',
                'EST_QTDMAX'    => '1',
                'EST_STA'       => '1',
            );
            
            $this->db->insert('ESTOQUE', $arr);   
        }
        
    }
    
}